package com.ns.scs.stat.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.core.mapper.IMapper;
import com.ns.core.utils.bean.ServiceUtil;
import com.ns.core.vo.bs.BaseVO;
import com.ns.scs.stat.dto.StatPageDto;
import com.ns.scs.stat.entry.StatEntry;
import com.ns.scs.stat.mapper.StatMapper;
import com.ns.scs.stat.service.IStatService;
import com.ns.scs.stat.vo.StatVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 图看板模块业务实现接口
 *
 * @author lw
 * @version : v1.0.0
 * @since 2024-11-08
 */
@Service
@RequiredArgsConstructor
public class StatServiceImpl extends ServiceImpl<StatMapper, StatEntry> implements IStatService {

    private final StatMapper mapper;

    @Override
    public Page<StatVO> getList(StatPageDto dto) {
        return mapper.getList(dto, new Page<>(dto.getCurrent(), dto.getSize()));
    }

    @Override
    public List<BaseVO> getOptions() {
        return mapper.getOptions();
    }

    @Override
    public Boolean syncStat(Long id) {
        Boolean flag = Boolean.TRUE;
        try {
            StatEntry statEntry = mapper.selectById(id);
            if (Objects.nonNull(statEntry) && Objects.nonNull(statEntry.getSqlExp())) {
                IMapper imapper = ServiceUtil.getBean(IMapper.class);
                Long count = imapper.getCountBySql(statEntry.getSqlExp());
                statEntry.setVariable(count - statEntry.getCount());
                statEntry.setCount(count);
                flag = mapper.insertOrUpdate(statEntry);
            }
        } catch (Exception e) {
            flag = Boolean.FALSE;
        }
        return flag;
    }
}
